<?php
/**
 * Created by PhpStorm.
 * User: 9ey
 * Date: 2019/5/19
 * Time: 18:06
 */

namespace App\Utils;


use Illuminate\Support\Arr;

class Security
{
    /**
     * 密文节点
     * @var null|string
     */
    protected $ciphertext = null;

    /**
     * 加密工具
     * @var null
     */
    protected $encryption = null;

    private $queryParams = false;

    /**
     * 初始化
     * Security constructor.
     */
    public function __construct()
    {
        $this->ciphertext = config('app.apiCiphertext');
        if (!config('app.apiDebug')) {
            $this->encryption = new Encryption();
        }
    }

    /**
     * 单个数据
     * @param $key
     * @param null $default
     * @return mixed
     */
    public function get($key, $default = null)
    {
        if (config('app.apiDebug')) {
            return request()->get($key, $default);
        } else {
            return Arr::get($this->all(), $key, $default);
        }
    }

    /**
     * 全部数据
     * @return mixed
     */
    public function all()
    {
        if (!$this->queryParams) {
            if (config('app.apiDebug')) {
                $this->queryParams = request()->all();
            } else {
                $this->queryParams = json_decode($this->encryption->decrypt(request()->get($this->ciphertext)), true);
            }
        }
        return $this->queryParams;

    }

    /**
     * 加密
     * @param array $array
     * @return array|string
     */
    public function encrypt(array $array)
    {
        if (config('app.apiDebug')) {
            return $array;
        } else {
            return $this->encryption->encrypt(json_encode($array));
        }
    }
    /**
     * 加密
     * @param array $array
     * @return array|string
     */
    public function encryptString($str)
    {
        if (config('app.apiDebug')) {
            return $str;
        } else {
            return $this->encryption->encrypt($str);
        }
    }
}
